from backend.backend import Backend
from workflow.task import Task
from workflow.flowData import Status

class RacketeeringBackend(Backend):
    #Stage = "NEW" 
    def __init__(self):
        Backend.__init__(self, "BreakALeg")
    def wire(self):
        self.register_result_listener("BossMan", "OwnerInfo", self.identify_owner)
        self.register_result_listener("BusinessOwner", "OwnerDecide", self.owner_decide)
        self.register_result_listener("Muscle", "TakeAction", self.muscle_decide)

        #   self.register_result_listener("BagMan", "Collect", self.collect_money)
        # self.register_result_listener("Hitman", "Execute", self.hitman_decide)

    def identify_owner(self,results):
        for result in results:
            task = Task.construct_from_result(result, "BusinessOwner", "OwnerDecide")
            task.set_field('TakeAction', 'None')
            task.set_field('attempts',1)
            self.workflow.add(task)
            self.workflow.update_status(result, Status.COMPLETE)
            
    def owner_decide(self,results):
        for result in results:
            if result.data['ownerdecide'] == 'Yes':
                # We accepted the protection.  Could send notification task to  BusinessOwner.
                pass;
            else:
                attempts = result.get_int_field('attempts')
                if attempts >= 3:
                    task = Task.construct_from_result(result, "Muscle", "Kill")
                else:
                    task = Task.construct_from_result(result, "Muscle", "TakeAction")                    
                self.workflow.add(task)
            self.workflow.update_status(result, Status.COMPLETE)

    def muscle_decide(self,results):
        for result in results:
            attempts = result.get_int_field('attempts')
            task = Task.construct_from_result(result, "BusinessOwner", "OwnerDecide")
            task.set_field('attempts', attempts+1)
            self.workflow.add(task)
            self.workflow.update_status(result, Status.COMPLETE)            

if __name__ == '__main__':
    backend = RacketeeringBackend()